package com.jiangnan.ui.activity

import android.os.Bundle
import android.widget.CompoundButton
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityAuthBinding
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.AuthViewModel

class AuthActivity : BaseActivity(), CompoundButton.OnCheckedChangeListener {

    private lateinit var binding: ActivityAuthBinding
    private lateinit var viewModel: AuthViewModel

    // 添加正则表达式，用于校验手机号和密码
    private val phoneRegex = Regex("^1[3-9]\\d{9}$")
    // 密码正则：仅允许数字、英文大小写、下划线、减号和@，长度6-20
    private val passwordRegex = Regex("^(?=.{6,20}$)[0-9A-Za-z_\\-@]+$")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 使用 DataBinding 设置布局
        binding = DataBindingUtil.setContentView(this, R.layout.activity_auth)
        // 获取 ViewModel 实例
        viewModel = ViewModelProvider(this).get(AuthViewModel::class.java)
        binding.viewModel = viewModel
        binding.lifecycleOwner = this

        // 点击发送验证码按钮
        binding.btnSendCode.setOnClickListener {
            val phone = binding.etPhone.text.toString().trim()
            if (phone.isEmpty()) {
                ToastUtil.showShort(this, "请输入手机号")
                return@setOnClickListener
            }
            if (!phoneRegex.matches(phone)) {
                ToastUtil.showShort(this, "请输入有效的手机号")
                return@setOnClickListener
            }
            // 调用 ViewModel 发送验证码
            viewModel.sendSmsCode(phone)
        }

        // 点击注册按钮
        binding.btnRegister.setOnClickListener {
            val phone = binding.etPhone.text.toString().trim()
            val smsCode = binding.etSmsCode.text.toString().trim()
            val password = binding.etPassword.text.toString().trim()
            val confirmPassword = binding.etConfirmPassword.text.toString().trim()

            // 非空校验
            if (phone.isEmpty() || smsCode.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
                ToastUtil.showShort(this, "请填写完整信息")
                return@setOnClickListener
            }
            // 手机号格式校验
            if (!phoneRegex.matches(phone)) {
                ToastUtil.showShort(this, "请输入有效的手机号")
                return@setOnClickListener
            }
            // 密码格式校验
            if (!passwordRegex.matches(password)) {
                ToastUtil.showShort(
                    this,
                    "密码只能由数字、英文字符、下划线、减号和@组成,长度为6-20"
                )
                return@setOnClickListener
            }
            // 检查两次密码是否一致
            if (password != confirmPassword) {
                ToastUtil.showShort(this, "两次密码输入不一致")
                return@setOnClickListener
            }
            // 检查是否同意协议
            if (!binding.cbAgree.isChecked) {
                binding.cbAgree.error = "请先同意协议"
                return@setOnClickListener
            }
            // 调用 ViewModel 注册用户
            viewModel.registerUser(phone, password, smsCode)
        }

        initObserve()
        toastMessage()

        binding.cbAgree.setOnCheckedChangeListener(this)
    }

    private fun initObserve() {
        // 观察倒计时 LiveData 更新发送验证码按钮状态
        viewModel.countdown.observe(this) { seconds ->
            if (seconds > 0) {
                binding.btnSendCode.isEnabled = false
                binding.btnSendCode.text = "$seconds 秒后重发"
            } else {
                binding.btnSendCode.isEnabled = true
                binding.btnSendCode.text = "发送验证码"
            }
        }

        // 观察发送验证码返回结果
        viewModel.smsResponse.observe(this) { res ->
            res?.let {
                if (it.code == 1) {
                    binding.tvMessage.text = "验证码已发送"
                } else {
                    binding.tvMessage.text = it.msg
                }
            }
        }

        // 观察注册返回结果
        viewModel.registerResponse.observe(this) { res ->
            res?.let {
                if (it.code == 1) {
                    binding.tvMessage.text = "注册成功"
                } else {
                    binding.tvMessage.text = it.msg
                }
            }
        }
    }

    private fun toastMessage() {
        viewModel.toastMessage.observe(this) { event ->
            event.getContentIfNotHandled()?.let { message ->
                ToastUtil.showShort(this, message)
            }
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        // 此处可根据需要处理协议复选框状态变化，目前暂不做处理
    }
}
